/**
 * Copyright 2008 Mathias Doenitz, http://lis.to/
 *
 * This file is part of the lis.to java desktop client. The lis.to java desktop client is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * The lis.to java desktop client is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with the lis.to java desktop client.
 * If not, see http://www.gnu.org/licenses/
 */

package listo.client.viewlists;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import listo.client.MenuBuilder;
import listo.client.actions.Actions;
import listo.client.model.Tasks;
import listo.client.taskfilters.AllTasksFilter;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;

@Singleton
public class AllTasksViewList extends ViewList {

    private final AllTasksView allTasksView;
    private final MenuBuilder menuBuilder;
    private final Actions actions;

    @Inject
    public AllTasksViewList(ViewListManager viewListManager, ViewListRenderer renderer, AllTasksFilter filter,
                            AllTasksView allTasksView, MenuBuilder menuBuilder, Actions actions) {
        super(viewListManager, renderer, null, filter);
        this.allTasksView = allTasksView;
        this.menuBuilder = menuBuilder;
        this.actions = actions;

        addFocusListener(new FocusAdapter() {
            public void focusGained(FocusEvent e) {
                setSelectedIndex(0);
            }
        });
    }

    public void tasksChanged(Object updateObject) {
        int selectedIndex = getSelectedIndex();

        Tasks tasks = (Tasks) updateObject;
        allTasksView.setTaskCount(tasks.size());
        setListData(new View[] {allTasksView});

        if (selectedIndex >= 0) {
            setSelectedIndex(selectedIndex);
        } else {
            clearSelection();
        }
    }

    protected void createPopupMenu(MouseEvent e) {
        if (!isFocusOwner()) requestFocusInWindow();
        menuBuilder.createPopupMenu(actions.addTaskAction).show(this, e.getX(), e.getY());
        e.consume();
    }
}
